package com.wzh.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;

public class HtmlJsoupUtil {

    public static Element getMaxContentEl(String html){
        Document document = Jsoup.parse(html);

        Elements list = document.select("p");

        Elements  brlist = document.select("br");
        list.addAll(brlist);


        Element _conte = getParentNodeMaxCount(list,new Integer(0)).getElement();

        return removeScript(_conte);
    }

    /**
     * 获取章节列表页面，小说的url
     * @param html
     * @param domain
     * @param charset
     * @return
     */
    public static List<String> getBookUrl(String html,String domain,String charset){
        Document document = Jsoup.parse(html);
        List<String> _result = new ArrayList<String>();

        Elements list = document.select("ul");
        if(list.size()>0){
            for(Element e:list){//循环ul 找到真正的 book list
                Elements elis = e.select("li");
                if(elis.size()>0 && elis.get(0).text().length()>10){
                    for(Element eli:elis){
                        Elements lias = eli.select("a");
                        for(Element a:lias){
                            //兼容特殊情况
                            if(a.attr("title").contains("小说") ||
                                    a.text().contains("小说") ||
                                    a.text().contains("[")){
                                continue;
                            }else {
                                String url = a.attr("href");

                                _result.add(getDominlink(url,domain));
                                break;
                            }
                        }
                    }
                }
            }


        }
        Elements next = document.select("a:contains(>)");
        Elements next_end = document.select("a:contains(>>)");
        Elements next1 =document.select("a:contains(下一页)");
        try {
            String webcontent = "";
            if (next.size() > 0 ) {
                String _u = getDominlink(next.get(0).attr("href"),domain);
                String _u_end = getDominlink(next_end.get(0).attr("href"),domain);
                if(!_u.equals(_u_end)){
                    webcontent = BookCollectUtil.getWebContentByUrl(_u,charset);
                }
            } else if (next1.size() > 0) {
                webcontent = BookCollectUtil.getWebContentByUrl(getDominlink(next1.get(0).attr("href"),domain),charset);
            }
            if(!"".equals(webcontent)) {
                _result.addAll(getBookUrl(webcontent, domain, charset));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return _result;
    }

    /**
     * 获取 book 总览页面，所有章节信息
     * @param contentJsoup
     * @param domain
     * @param charset
     * @return
     */
    public static LinkedHashMap     getBookCapterLink(BookCollectUtil.ContentJsoup contentJsoup,String domain,String charset){
        LinkedHashMap _re = new LinkedHashMap();
        Document document = contentJsoup.getDocument();
        String _aselect = "a:matches(第([\\s\\S]*)章)";
        //获取上级包含最多的 a 且 第 章，最多上面4级别
        Elements  alist = document.select(_aselect);
        Integer maxcount = 0;
        HtmlJsoupUtil.ElementCount elementCount = getParentNodeMaxCount(alist,maxcount);

        Element _conte = elementCount.getElement();
        maxcount = elementCount.getCount();
        if(maxcount<20){
            elementCount = getParentNodeMaxCount(alist.parents(),0);
            _conte = elementCount.getElement();
            maxcount = elementCount.getCount();
            if(maxcount<20){
                elementCount = getParentNodeMaxCount(alist.parents().parents(),maxcount);//最多支持三级
                _conte = elementCount.getElement();
            }
        }

        //如果少于 20个，则，寻找 “阅读” 的连接，在进行相关操作
        Elements  aparent = _conte.select(_aselect);
        if(aparent.size()<20){
            String _more_select = "a:contains(阅读)";
            Elements  _more_selects = document.select(_more_select);
            if(_more_selects.size()>0){
                String moreurl = getDominlink(_more_selects.get(0).attr("href"),domain);
                BookCollectUtil.ContentJsoup newdoc = BookCollectUtil.getWebContentDocumentByUrl(moreurl,charset);
                _re.putAll(getBookCapterLink(newdoc,domain,charset));
            }
        }
        for (Element e:aparent){
            String url1 = getDominlink(e.attr("abs:href"),domain);
            if(url1 ==null ||"".equals(url1)){
                url1 = getDominlink(e.attr("href"),domain);
            }
            String text = e.text();
            _re.put(url1,text);
        }

        return _re;
    }

    static class  ElementCount{
        public Element element = Jsoup.parse("");
        public Integer count = 0;

        public Element getElement() {
            return element;
        }

        public void setElement(Element element) {
            this.element = element;
        }

        public Integer getCount() {
            return count;
        }

        public void setCount(Integer count) {
            this.count = count;
        }
    }

    /**
     * 根据元素列表，将父节点计数，看那个父节点下 对应元素最多
     * @param list
     * @param maxnum
     * @return
     */
    public static ElementCount getParentNodeMaxCount(Elements list,Integer maxnum){
        ElementCount _r = new ElementCount();
        Map<Element,Integer> _mp = new HashMap<Element,Integer>();
        for(Element e:list){
            Element p = e.parent();//标签p的上一级含有文本最多的 元素
            if(_mp.keySet().contains(p)){
                Integer newcount = _mp.get(p) + 1;
                _mp.put(p, newcount);//把上级放入key，计算p的上级的次数，找到包含p多的
                if(_mp.get(p)+1>maxnum){
                    _r.setCount(newcount);
                    _r.setElement(p);
                }
            }else {
                _mp.put(p, 1);
            }
        }
        return _r;
    }

    /**
     * 获取完整url
     * @param url
     * @param domain
     * @return
     */
    public static String getDominlink(String url,String domain){
        if ((url != null) && (!url.startsWith("http")) &&
                (domain != null)) {
            url = "http://" + domain + url;
        }
        return url;
    }


    /**
     * 去除js
     * @param _conte
     * @return
     */
    public static Element removeScript(Element _conte){
        List<Element> elementList = _conte.select("script");
        for(Element e :elementList){
            e.remove();
        }
        return _conte;
    }


}
